package com.xiaoshuidi.cloud.module.rooms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoshuidi.cloud.framework.common.exception.ErrorCode;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.estimate.vo.*;
import com.xiaoshuidi.cloud.module.rooms.convert.estimate.EstimateConvert;
import com.xiaoshuidi.cloud.module.rooms.enums.EstimateStatus;
import com.xiaoshuidi.cloud.module.rooms.enums.EstimateSurveyTypeEnum;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomHouseEstimate;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomHouseEstimateInfo;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomHouseType;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomHouseEstimateInfoRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomHouseEstimateRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomHouseTypeRepository;
import com.xiaoshuidi.cloud.module.rooms.service.IEstimateService;
import com.xiaoshuidi.cloud.module.rooms.service.RoomHouseTypeService;
import com.xiaoshuidi.cloud.module.rooms.utils.PVUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Feng
 * @date 2023/5/29
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class EstimateServiceImpl implements IEstimateService {

    private final RoomHouseEstimateRepository estimateRepository;
    private final RoomHouseEstimateInfoRepository estimateInfoRepository;
    private final RoomHouseTypeService roomHouseTypeService;
    private final RoomHouseTypeRepository roomHouseTypeRepository;
    /**
     * 房屋勘测 硬装占比
     */
    private final static double survey_y_proportion = 0.5;
    /**
     * 房屋勘测 家具占比
     */
    private final static double survey_j_proportion = 0.2;
    /**
     * 房屋勘测 家电占比
     */
    private final static double survey_d_proportion = 0.3;

    @Override
    public SurveyResp surveyFactor(SurveyReq req) {
        List<SurveyInfoVo> list = new ArrayList<>();
        List<SurveyReq.Info> infos = req.getInfoList();
        if (CollectionUtil.isNotEmpty(infos)) {
            surveyValid(infos, list);
        }
        SurveyResp resp = new SurveyResp();
        if (CollectionUtil.isEmpty(list)) {
            return resp;
        }

        double y = BigDecimal.valueOf(list.stream()
                        .filter(s -> EstimateSurveyTypeEnum.Y.getCode().equals(s.getType()))
                        .mapToDouble(SurveyInfoVo::getFactor).average().getAsDouble())
                .setScale(2, RoundingMode.HALF_UP).doubleValue();
        double j = BigDecimal.valueOf(list.stream()
                        .filter(s -> EstimateSurveyTypeEnum.J.getCode().equals(s.getType()))
                        .mapToDouble(SurveyInfoVo::getFactor).average().getAsDouble())
                .setScale(2, RoundingMode.HALF_UP).doubleValue();
        double d = BigDecimal.valueOf(list.stream()
                        .filter(s -> EstimateSurveyTypeEnum.D.getCode().equals(s.getType()))
                        .mapToDouble(SurveyInfoVo::getFactor).average().getAsDouble())
                .setScale(2, RoundingMode.HALF_UP).doubleValue();
        // 硬装占比 50%， 家具占比%20， 家电占比30%
        double factor = y * survey_y_proportion + j * survey_j_proportion + d * survey_d_proportion;
        resp.setInfoList(infos);
        resp.setD(d);
        resp.setJ(j);
        resp.setY(y);
        resp.setFactor(BigDecimal.valueOf(factor).setScale(2, RoundingMode.HALF_UP).doubleValue());
        return resp;
    }

    public void surveyValid(List<SurveyReq.Info> infos, List<SurveyInfoVo> list) {
        if (CollectionUtil.isNotEmpty(infos)) {
            infos.forEach(s -> {
                if (CollectionUtil.isEmpty(s.getInfo())) {
                    throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), String.format("%s评分不能为空", s.getName()));
                }
                if (s.getInfo().stream().anyMatch(vo -> vo.getFactor() > 1 || vo.getFactor() < 0)) {
                    throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "系数范围为0-1");
                }
                list.addAll(s.getInfo());
            });
        }
    }

    @Override
    public BasicPriceResp basicPrice(BasicPriceReq req) {
        List<BasicPriceReq.Info> list = req.getList();
        BasicPriceResp resp = new BasicPriceResp();
        if (CollectionUtil.isEmpty(list)) {
            return resp;
        }
        if (list.size() < 6) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "样本数不能少于6个");
        }
        if (list.size() > 10) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "样本数不能大于10个");
        }
        if (list.stream().anyMatch(s -> s.getPrice() < 0)) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "样本价格不能小于0");
        }
        double min = list.stream().mapToDouble(BasicPriceReq.Info::getPrice).min().getAsDouble();
        double max = list.stream().mapToDouble(BasicPriceReq.Info::getPrice).max().getAsDouble();
        double sum = list.stream().mapToDouble(BasicPriceReq.Info::getPrice).sum();
        //基础价 去掉最高价和最低价 （样本1+样本2+样本3+样本N）/样本数N
        sum = sum - max - min;
        double basicPrice = BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(list.size() - 2), 2, RoundingMode.HALF_UP).doubleValue();
        resp.setList(list);
        resp.setBasicPrice(basicPrice);
        return resp;
    }

    @Override
    public DecorationEvaluateResp decorationEvaluate(DecorationEvaluateReq req) {
        List<DecorationEvaluateReq.Info> list = req.getList();
        DecorationEvaluateResp resp = new DecorationEvaluateResp();
        if (CollectionUtil.isEmpty(list)) {
            return resp;
        }
        if (list.stream().anyMatch(s -> s.getAvgPrice() < 0 || s.getTotalPrice() < 0)) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "存在价格小于0");
        }
        //总价
        double totalPrice = BigDecimal.valueOf(list.stream().mapToDouble(s -> s.getAvgPrice() * s.getNumber()).sum()).setScale(2, RoundingMode.HALF_UP).doubleValue();

        resp.setList(list);
        resp.setDecorationEvaluate(totalPrice);
        return resp;
    }

    @Override
    public RentEvaluateResp rentEvaluate(RentEvaluateReq req) {
        List<RentEvaluateReq.Info> list = req.getList();
        RentEvaluateResp resp = new RentEvaluateResp();
        if (CollectionUtil.isEmpty(list)) {
            return resp;
        }
        if (list.stream().anyMatch(s -> s.getFactor() < 0 || s.getFactor() > 1.3)) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "系数范围为0-1.3");
        }
        if (list.stream().anyMatch(s -> s.getFactorRatio() < 0 || s.getFactorRatio() > 1)) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "系数占比为0-100");
        }
        //系数终值 楼层系数*系数占平+楼层系数*系数占比+淡旺季系数*系数占比+装修状况系数*系数占比
        double finalFactor = BigDecimal.valueOf(list.stream().mapToDouble(s -> s.getFactorRatio() * s.getFactor()).sum()).setScale(2, RoundingMode.HALF_UP).doubleValue();
        //租金估值 房屋基准价*系数终值
        double estimatePrice = BigDecimal.valueOf(req.getBasicPrice() * finalFactor).setScale(2, RoundingMode.HALF_UP).doubleValue();
        resp.setList(list);
        resp.setEstimatePrice(estimatePrice);
        resp.setFinalFactor(finalFactor);
        resp.setBasicPrice(req.getBasicPrice());
        return resp;
    }


    /**
     * 合理利润 10%
     */
    private final static double highest_price_profit = 0.1;

    @Override
    public HighestPriceResp highestPrice(HighestPriceReq req) {

        double deductionA = 0;
        if (req.getDecorationEvaluate() != null && !req.getDecorationEvaluate().equals(0d) && req.getAmortizationPeriod() != null &&
                req.getAmortizationPeriod() != 0) {
            deductionA = BigDecimal.valueOf(req.getDecorationEvaluate()).divide(BigDecimal.valueOf(req.getAmortizationPeriod()), 2, RoundingMode.HALF_UP).doubleValue();
        }
        double deductionB = Math.abs(PVUtil.fv(req.getInterestRate(), req.getPc(), -req.getEstimatePrice(), req.getEstimatePrice() * req.getPc(), 1));
        double highestPrice = BigDecimal.valueOf(req.getEstimatePrice() * (1 - highest_price_profit) - deductionA - deductionB).setScale(2, RoundingMode.HALF_UP).doubleValue();
        HighestPriceResp resp = new HighestPriceResp();
        BeanUtils.copyProperties(req, resp);
        resp.setHighestPrice(highestPrice);
        resp.setDeductionA(deductionA);
        resp.setDeductionB(deductionB);
        return resp;
    }

    @Override
    @Transactional
    public Boolean saveOrUpdate(EstimateSaveOrUpdateReq req) {
        Long id = req.getId();
        RoomHouseEstimate estimate;
        RoomHouseEstimateInfo estimateInfo = new RoomHouseEstimateInfo();
        if (id != null) {
            estimate = estimateRepository.getById(id);
            estimateInfo = estimateInfoRepository.getByEstimateId(id);
        }
        estimate = EstimateConvert.INSTANCE.convert(req);
        estimateInfo.setDeptId(req.getDeptId());
        //计算房屋勘测系数
        if (ObjectUtil.isNotEmpty(req.getSurveyReq())) {
            SurveyResp surveyResp = this.surveyFactor(req.getSurveyReq());
            estimateInfo.setSurveyJson(JsonUtils.toJsonString(surveyResp));
        }
        //基准价计算
        if (ObjectUtil.isNotEmpty(req.getBasicPriceReq())) {
            BasicPriceResp basicPriceResp = this.basicPrice(req.getBasicPriceReq());
            estimateInfo.setBasicPriceJson(JsonUtils.toJsonString(basicPriceResp));
        }
        //装修估价计算
        if (req.getIsAlteration() && ObjectUtil.isNotEmpty(req.getDecorationEvaluateReq())) {
            DecorationEvaluateResp decorationEvaluateResp = this.decorationEvaluate(req.getDecorationEvaluateReq());
            estimateInfo.setDecorationEvaluateJson(JsonUtils.toJsonString(decorationEvaluateResp));
        }
        //租金估算计算
        if (ObjectUtil.isNotEmpty(req.getRentEvaluateReq())) {
            RentEvaluateResp rentEvaluateResp = this.rentEvaluate(req.getRentEvaluateReq());
            estimateInfo.setFactorJson(JsonUtils.toJsonString(rentEvaluateResp));
        }
        //最高价格 扣减因素计算
        if (ObjectUtil.isNotEmpty(req.getHighestPriceReq())) {
            HighestPriceResp highestPriceResp = this.highestPrice(req.getHighestPriceReq());
            double highestPrice = highestPriceResp.getHighestPrice();
            estimate.setHighestPrice(highestPrice);
            estimateInfo.setDeductionFactorsJson(JsonUtils.toJsonString(highestPriceResp));
            estimate.setStatus(EstimateStatus.CALCULATED.getCode());
        } else {
            //如果是新增且未计算出最高价格，则为待测算
            if (id == null)
                estimate.setStatus(EstimateStatus.TO_BE_CALCULATED.getCode());
        }
        //获取户型
        RoomHouseType roomHouseType = roomHouseTypeService.getRoomHouseType(req.getBedRoomNum(),
                req.getLivingRoomNum(),
                req.getToiletNum(),
                req.getKitchenNum(),
                req.getBalcony());
        estimate.setRoomHouseTypeId(roomHouseType.getId());
        estimateRepository.saveOrUpdate(estimate);
        estimateInfo.setEstimateId(estimate.getId());
        estimateInfoRepository.saveOrUpdate(estimateInfo);
        return true;
    }


    @Override
    public EstimateResp get(Long id) {
        RoomHouseEstimate estimate = estimateRepository.getById(id);
        if (ObjectUtil.isEmpty(estimate)) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "该测算不存在");
        }
        RoomHouseEstimateInfo estimateInfo = estimateInfoRepository.getByEstimateId(id);
        RoomHouseType houseType = roomHouseTypeRepository.getById(estimate.getRoomHouseTypeId());
        EstimateResp resp = EstimateConvert.INSTANCE.convert(estimate);
        resp.setBasicPriceResp(JSONObject.parseObject(estimateInfo.getBasicPriceJson(), BasicPriceResp.class));
        resp.setDecorationEvaluateResp(JSONObject.parseObject(estimateInfo.getDecorationEvaluateJson(), DecorationEvaluateResp.class));
        resp.setSurveyResp(JSONObject.parseObject(estimateInfo.getSurveyJson(), SurveyResp.class));
        resp.setHighestPriceResp(JSONObject.parseObject(estimateInfo.getDeductionFactorsJson(), HighestPriceResp.class));
        resp.setRentEvaluateResp(JSONObject.parseObject(estimateInfo.getFactorJson(), RentEvaluateResp.class));
        resp.setBedRoomNum(houseType.getBedRoomNum());
        resp.setToiletNum(houseType.getToiletNum());
        resp.setKitchenNum(houseType.getKitchenNum());
        resp.setLivingRoomNum(houseType.getLivingRoomNum());
        resp.setBalcony(houseType.getBalcony());
        return resp;
    }

    @Override
    public PageResult<EstimatePageResp> page(EstimatePageReq req) {

        PageResult<EstimateListResp> pageResult = estimateRepository.page2(req.getSearch(), req.getPageNo(), req.getPageSize());
        List<EstimateListResp> records = pageResult.getList();
        if (CollectionUtil.isEmpty(records)) {
            return new PageResult<>();
        }
        List<Long> houseTypeIds = records.stream().map(RoomHouseEstimate::getRoomHouseTypeId).collect(Collectors.toList());
        Map<Long, String> houseTypeMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(houseTypeIds)) {
            List<RoomHouseType> houseTypeList = roomHouseTypeRepository.listByIds(houseTypeIds);
            if (CollectionUtil.isNotEmpty(houseTypeList)) {
                houseTypeMap = houseTypeList.stream().collect(Collectors.toMap(RoomHouseType::getId, RoomHouseType::getName, (s1, s2) -> s1));
            }
        }
        Map<Long, String> finalHouseTypeMap = houseTypeMap;
        List<EstimatePageResp> resps = records.stream().map(s -> {
            EstimatePageResp resp = new EstimatePageResp();
            resp.setHouseAddress(String.format("%s%s栋%s单元%s号", s.getArea(), s.getBuildingNo(), s.getUnitNo(), s.getRoomHouseNo()));
            if(ObjectUtil.isNotEmpty(s.getRoomId())){
                resp.setRelatedHouseAddress(String.format("%s%s栋%s单元%s号", s.getRelatedArea(), s.getRelatedBuildingNo(), s.getRelatedUnitNo(), s.getRelatedRoomHouseNo()));
            }
            resp.setHouseType(finalHouseTypeMap.get(s.getRoomHouseTypeId()));
            resp.setHighestPrice(s.getHighestPrice() == null ? "" : BigDecimal.valueOf(s.getHighestPrice()).setScale(2, RoundingMode.HALF_UP).toString());
            resp.setStatus(s.getStatus());
            resp.setId(s.getId());
            resp.setStatusStr(EstimateStatus.getNameByCode(s.getStatus()));
            return resp;
        }).collect(Collectors.toList());
        PageResult<EstimatePageResp> result = new PageResult<>(resps, pageResult.getTotal());
        return result;
    }

    @Override
    public Boolean relatedHouse(RelatedHouseReq req) {
        RoomHouseEstimate byId = estimateRepository.getById(req.getId());
        if (ObjectUtils.isEmpty(byId)) {
            throw new ServiceException(new ErrorCode(4001, "此测算不存在"));
        }
        //校验这个房源id已经关联其他测算了
        List<RoomHouseEstimate> list = estimateRepository.getListByRoomId(req);
        if (!CollectionUtils.isEmpty(list)) {
            throw new ServiceException(new ErrorCode(4002, "此房源已关联其他测算"));
        }
        RoomHouseEstimate roomHouseEstimate = new RoomHouseEstimate();
        roomHouseEstimate.setId(req.getId());
        roomHouseEstimate.setRoomId(req.getRoomId());
        return estimateRepository.updateById(roomHouseEstimate);
    }
}
